package com.odm.communitymanage.ui.login

import android.os.Bundle
import android.widget.Toast
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.odm.communitymanage.R
import com.odm.communitymanage.base.BaseMVVMFragment
import com.odm.communitymanage.core.Constants
import com.odm.communitymanage.core.bean.LoginRegisterCallback
import com.odm.communitymanage.core.bean.NetCallBack
import com.odm.communitymanage.core.bean.PostRegisterData
import com.odm.communitymanage.core.net.ApiService
import com.odm.communitymanage.ui.HomeFragment
import com.rxjava.rxlife.lifeOnMain
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.fragment_replenish_info.*
import me.yokeyword.fragmentation.ISupportFragment
import rxhttp.wrapper.param.RxHttp


/**
 * @description: 完善信息页面
 * @author: ODM
 * @date: 2020/4/16
 */
class ReplenishInfoFragment : BaseMVVMFragment() {

    lateinit var phoneNumber : String
    lateinit var passCode : String

    var disposable : Disposable ?= null

    override fun initViewModelObserve() {

    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        getTransitiveData()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        //销毁请求
        if(false == disposable?.isDisposed){
            disposable?.dispose()
        }
    }

    override fun initViews() {
        tvChooseCommunity_ReplenishInfo.setOnClickListener {
            getCommunityName()
        }
        //提交信息 按钮的点击事件
        btnPost_ReplenishInfo.setOnClickListener {
            hideSoftInput()
            postRegister()
        }
    }

    private fun getTransitiveData() {
        // 获取由启动者Fragment传递过来的String类型数据
        phoneNumber = arguments?.getString(Constants.USER_PHONE_NUMBER) as String
        passCode = arguments?.getString(Constants.USER_PASSWORD) as String
    }


    private fun getCommunityName() {
        // 启动
        startForResult(SearchCommunityFragment(), Constants.REQUEST_COMMUNITY_NAME_CODE)
        hideSoftInput()
    }

    // 目标Fragment调用setFragmentResult()后，在其出栈时，会回调该方法
    override fun onFragmentResult(requestCode: Int, resultCode: Int, data: Bundle?) {
        super.onFragmentResult(requestCode, resultCode, data)
        if (requestCode == Constants.REQUEST_COMMUNITY_NAME_CODE && resultCode == ISupportFragment.RESULT_OK) {
            // 在此通过Bundle data 获取返回的数据
            etCommunityName_ReplenishInfo.setText(data?.getString(Constants.SELECTED_COMMUNITY_NAME))
        }
    }

    /**
     * 提交完整的信息，进行注册请求
     */
    private fun postRegister(){
        val name  = etName_ReplenishInfo.text.toString()
        val communityName = etCommunityName_ReplenishInfo.text.toString()
        val idCardNumber = etCardNumber_ReplenishInfo.text.toString()
        //信息判空提醒
        if(name == "" || communityName == "" || idCardNumber == ""){
            ToastUtils.showLong("请填写完整的信息")
            return
        }
        disposable = RxHttp.postJson(ApiService.REGISTER)
            .addAll(GsonUtils.toJson(PostRegisterData(idCardNumber, name ,passCode ,phoneNumber, communityName)))
            .asObject(LoginRegisterCallback::class.java)
            .lifeOnMain(this)
            .subscribe({
                if(it.code == 1){
                    ToastUtils.showShort("注册成功")
                    //注册成功后，存储本地用户信息，进入首页
                    SPUtils.getInstance(Constants.SP_USER).put(Constants.USER_NAME , it.data.name)
                    SPUtils.getInstance(Constants.SP_USER).put(Constants.USER_COMMUNITY_NAME , it.data.villageName)
                    SPUtils.getInstance(Constants.SP_USER).put(Constants.USER_ID_CARD , it.data.idcard)
                    enterHome()
                }else{
                    ToastUtils.showLong(it.message)
                }
            },{
                ToastUtils.showLong(it.message)
                LogUtils.e(it.message)
            })
    }

    /**
     * 从注册页进入首页
     */
    private fun enterHome(){
        LiveEventBus
            .get("loadHome")
            .post("loadHome")
        SPUtils.getInstance(Constants.SP_USER).put(Constants.USER_PHONE_NUMBER , phoneNumber)
        startWithPop(HomeFragment())
        hideSoftInput()
    }




    override fun getLayoutId(): Int {
        return R.layout.fragment_replenish_info
    }
}